package com.chart.web.controller.chart.sta;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.chart.chart.domian.ChartConfigs;
import com.chart.chart.domian.dto.ChartDateTto;
import com.chart.chart.domian.vo.ChartSmartVo;
import com.chart.chart.service.IChartConfigsService;
import com.chart.common.core.controller.BaseController;
import com.chart.common.core.domain.AjaxResult;
import com.chart.common.utils.ChartDataUtils;
import com.chart.common.utils.ExcelDataUtils;
import com.chart.common.utils.ExcelUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.chart.web.controller.chart.sta.JsonsUtil.extractDataFromListNullString;
import static com.chart.web.controller.chart.sta.JsonsUtil.updateLegendDataNames;
import static com.chart.web.controller.chart.sta.LineChartController.extractDataFromList;

/**
 * 盒须图
 *
 * @author chart
 */
@RestController
@RequestMapping("/boxWhiskers/chart")
public class BoxWhiskersChartController extends BaseController {


    @Autowired
    private IChartConfigsService chartConfigsService;


/*好用的 不完全
    //盒须图
    @PostMapping("/importData1")
    public AjaxResult importData(@RequestBody ChartDateTto chartDateTto) throws Exception {
        // 提取数据
        List<List<String>> getdata = extractDataFromListNullString(chartDateTto.getDataList());
        ArrayList<String> seriesName = new ArrayList<>();

        // 遍历 excel 的每一行数据
        for (int rowIndex = 0; rowIndex < getdata.size(); rowIndex++) {
            List<String> row = getdata.get(rowIndex);
            System.out.println("正在处理第 " + (rowIndex + 1) + " 行:");

            String s = row.get(0); // 第一行第一列的数据放入集合中
            seriesName.add(s);

            // 遍历当前行中的每一列
            for (int colIndex = 0; colIndex < row.size(); colIndex++) {
                String cellValue = row.get(colIndex);
                System.out.println("  第 " + (colIndex + 1) + " 列: " + cellValue);
            }
        }

        String chartValue = chartDateTto.getChartValue();
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(chartValue);
        JsonNode datasetNode = rootNode.path("dataset");

        // 创建新的source数组
        ArrayNode newSourceArray = objectMapper.createArrayNode();

        // 遍历 dataset 中的每一个对象
        if (datasetNode.isArray()) {
            for (JsonNode datasetElement : datasetNode) {
                JsonNode sourceNode = datasetElement.path("source");

                // 如果 source 节点存在并且是数组
                if (sourceNode.isArray()) {
                    for (JsonNode rowArray : sourceNode) {
                        // 复制当前行的数组，并移除第一个元素
                        ArrayNode newRowArray = objectMapper.createArrayNode();
                        for (int i = 1; i < rowArray.size(); i++) {
                            newRowArray.add(rowArray.get(i));
                        }
                        newSourceArray.add(newRowArray);
                    }

                    // 更新 dataset 中的 source
                    ((ObjectNode) datasetElement).set("source", newSourceArray);
                }
            }
        }
        ArrayList<ChartSmartVo> newList = new ArrayList<>();
        ChartSmartVo chartSmartVo = new ChartSmartVo();
        chartSmartVo.setConfigValue(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode));
        newList.add(chartSmartVo);
        System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode).toString());
        return AjaxResult.success(newList);

    }*/

    /**
     * 基础盒须图
     *
     * @param chartDateTto
     * @return
     * @throws Exception
     */
    @PostMapping("/importData1")
    public AjaxResult importData(@RequestBody ChartDateTto chartDateTto) throws Exception {
        // 提取数据
        List<List<String>> getdata = extractDataFromListNullString(chartDateTto.getDataList());


        List<String> lenNameList = getdata.get(0);
        lenNameList.remove(0);

        String chartValue = chartDateTto.getChartValue();
        // 删除第一行的数据
        getdata.remove(0);
        // 删除每行的第一列数据
        for (List<String> getdatum : getdata) {
            getdatum.remove(0);
        }
        // 按列分组
        int columnCount = getdata.get(0).size();
        List<List<Double>> groupedData = new ArrayList<>();

        for (int i = 0; i < columnCount; i++) {
            List<Double> columnData = new ArrayList<>();
            for (List<String> row : getdata) {
                columnData.add(Double.parseDouble(row.get(i)));
            }
            groupedData.add(columnData);
        }
        // 解析 chartValue
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(chartValue);
        // 找到 dataset 中的 source 数组
        JsonNode datasetNode = rootNode.path("dataset");
        if (datasetNode.isArray()) {
            for (JsonNode dataset : datasetNode) {
                JsonNode sourceNode = dataset.path("source");
                if (sourceNode.isMissingNode()) {
                    // 如果 source 节点不存在，创建一个空的 ArrayNode
                    sourceNode = objectMapper.createArrayNode();
                    ((ObjectNode) dataset).set("source", sourceNode);
                }

                if (sourceNode.isArray()) {
                    ArrayNode sourceArray = (ArrayNode) sourceNode;
                    sourceArray.removeAll(); // 清空原有的 source 数组

                    // 将 groupedData 添加到 source 数组中
                    for (List<Double> columnData : groupedData) {
                        ArrayNode arrayNode = objectMapper.createArrayNode();
                        for (Double value : columnData) {
                            arrayNode.add(value);
                        }
                        sourceArray.add(arrayNode);
                    }
                } else {
                    throw new IllegalArgumentException("source 节点不是一个数组");
                }
            }
        } else {
            throw new IllegalArgumentException("dataset 节点不是一个数组");
        }
     // 删除 series 数组中每个对象的 itemStyle 下的 color 键值对
        JsonNode seriesNode = rootNode.path("series");
        if (seriesNode.isArray()) {
            for (JsonNode seriesElement : seriesNode) {
                JsonNode itemStyleNode = seriesElement.path("itemStyle");
                if (itemStyleNode.isObject()) {
                    ((ObjectNode) itemStyleNode).remove("borderColor");
                }
            }
        }

        // 将修改后的 JSON 转换为字符串并返回
        String updatedChartValue = objectMapper.writeValueAsString(rootNode);
        ArrayList<ChartSmartVo> newList = new ArrayList<>();
        ChartSmartVo chartSmartVo = new ChartSmartVo();
        chartSmartVo.setConfigValue(updatedChartValue);
        chartSmartVo.setUniList(lenNameList);
        newList.add(chartSmartVo);
        return AjaxResult.success(newList);

    }


    // 要求获取dataset里面的source数组 里面的每个数组的内容为         List<List<Double>> groupedData = new ArrayList<>();里面的数据

    //要求保持dataset里面的其他内容不变 只对dataset的source进行修改

    //要求获取   String s = row.get(0); 的数量 对series里面的对象进行复制  并依次修改  series的name的值为seriesName的值




    /*    好用的基础盒形图//盒须图
  @PostMapping("/importData1")
    public AjaxResult importData(@RequestBody ChartDateTto chartDateTto) throws Exception {

        Sheet sheet = ExcelDataUtils.convertDataListToSheetsa(chartDateTto.getDataList());
        String chartValue = chartDateTto.getChartValue();

        // 获取数据
        List<List<String>> getdata = ExcelDataUtils.getData(sheet);
        if (CollectionUtils.isEmpty(getdata)) {
            return AjaxResult.error("请填充数据");
        }
        List<String> groupName = new ArrayList<>();
        List<List<Object>> gruopDatas = new ArrayList<>();

        // 解析 JSON 配置
        JSONObject jsonObject = JSON.parseObject(chartValue);
        List<JSONObject> dataset = (List<JSONObject>) jsonObject.get("dataset");

        List<JSONObject> datasetList = new ArrayList<>();

        for (int i = 1; i < getdata.size(); i++) {
            List<Object> gruopData = new ArrayList<>();
            List<String> colData = new ArrayList<>();
            List<String> data = getdata.get(i);
            for (String s : data) {
                if (!ObjectUtils.isEmpty(s) && !s.equals("")) {
                    colData.add(s);
                }
            }

            if (!CollectionUtils.isEmpty(colData)) {
                if (i == getdata.size() - 1) {
                    JSONObject jsonObject1 = new JSONObject();
                    for (String s : colData) {
                        gruopData.add(Double.parseDouble(s));
                    }
                    gruopDatas.add(gruopData);
                    jsonObject1.put("source", gruopDatas);
                    datasetList.add(jsonObject1);
                } else if (i == 1) {
                    groupName.add(colData.get(0));
                } else {
                    if (colData.size() == 1) {
                        groupName.add(colData.get(0));
                        JSONObject jsonObject1 = new JSONObject();
                        jsonObject1.put("source", gruopDatas);
                        datasetList.add(jsonObject1);
                        gruopDatas = new ArrayList<>();
                    } else {
                        for (String s : colData) {
                            gruopData.add(Double.parseDouble(s));
                        }
                        gruopDatas.add(gruopData);
                    }
                }
            }
        }

        List<JSONObject> series = (List<JSONObject>) jsonObject.get("series");
        ArrayList<JSONObject> seriesList = new ArrayList<>();
        JSONObject jsonObject1 = series.get(0);

        JSONObject jsonObject2 = dataset.get(dataset.size() - 1);
        for (int i = 0; i < groupName.size(); i++) {
            JSONObject jsonObject3 = new JSONObject();
            jsonObject3.putAll(jsonObject2);
            jsonObject3.put("fromDatasetIndex", i);
            datasetList.add(jsonObject3);

            JSONObject jsonObject4 = new JSONObject();
            jsonObject4.putAll(jsonObject1);
            jsonObject4.put("name", groupName.get(i));
            jsonObject4.put("datasetIndex", i + groupName.size());
            seriesList.add(jsonObject4);
        }
        jsonObject.put("dataset", datasetList);
        jsonObject.put("series", seriesList);
        // 处理 legend 部分


        Object legendObject = jsonObject.get("legend");
        if (legendObject instanceof JSONObject) {
            JSONObject legend = (JSONObject) legendObject;
            Object existingData = legend.get("data");
            if (existingData instanceof JSONArray) {
                JSONArray dataArray = (JSONArray) existingData;
                dataArray.clear();  // Clear existing data
                for (String name : groupName) {
                    JSONObject map = new JSONObject();
                    map.put("name", name);
                    dataArray.add(map);
                }
            } else {
                ArrayList<Map> maps = new ArrayList<>();
                for (String name : groupName) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("name", name);
                    maps.add(map);
                }
                legend.put("data", maps);
            }
            jsonObject.put("legend", legend);
        } else if (legendObject instanceof JSONArray) {
            JSONArray legendArray = (JSONArray) legendObject;
            for (int i = 0; i < legendArray.size(); i++) {
                JSONObject legendItem = legendArray.getJSONObject(i);
                Object existingData = legendItem.get("data");
                if (existingData instanceof JSONArray) {
                    JSONArray dataArray = (JSONArray) existingData;
                    dataArray.clear();  // Clear existing data
                    for (String name : groupName) {
                        JSONObject map = new JSONObject();
                        map.put("name", name);
                        dataArray.add(map);
                    }
                } else {
                    ArrayList<Map> maps = new ArrayList<>();
                    for (String name : groupName) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("name", name);
                        maps.add(map);
                    }
                    legendItem.put("data", maps);
                }
            }
            jsonObject.put("legend", legendArray);
        } else {
            System.err.println("Unexpected type for 'legend': " + legendObject.getClass().getSimpleName());
        }
*/

/*        Object legendObject = jsonObject.get("legend");
        if (legendObject instanceof JSONObject) {
            JSONObject legend = (JSONObject) legendObject;
            ArrayList<Map> maps = new ArrayList<>();
            for (String name : groupName) {
                Map<String, Object> map = new HashMap<>();
                map.put("name", name);
                maps.add(map);
            }
            legend.put("data", maps);
            jsonObject.put("legend", legend);
        } else if (legendObject instanceof JSONArray) {
            JSONArray legendArray = (JSONArray) legendObject;
            // 处理 legendArray 的逻辑 (根据需求修改)
            // 示例：
            ArrayList<Map> maps = new ArrayList<>();
            for (String name : groupName) {
                Map<String, Object> map = new HashMap<>();
                map.put("name", name);
                maps.add(map);
            }
            // 创建一个新的 JSONObject 用于更新 legendArray
            JSONObject newLegend = new JSONObject();
            newLegend.put("data", maps);
            jsonObject.put("legend", newLegend);
        } else {
            System.err.println("Unexpected type for 'legend': " + legendObject.getClass().getSimpleName());
        }*/


/*        ArrayList<ChartSmartVo> newList = new ArrayList<>();
        ChartSmartVo chartSmartVo = new ChartSmartVo();
        chartSmartVo.setConfigValue(JSON.toJSONString(jsonObject));
        newList.add(chartSmartVo);
        return AjaxResult.success(newList); }*/


    //盒须图
    @PostMapping("/v2/importData1")
    public AjaxResult v2importData(@RequestBody List<Map<String, Object>> dataLists, Long configId) throws
            Exception {
        //      XSSFWorkbook workbook = null;
        try {
/*            workbook = new XSSFWorkbook(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(1);*/

            Sheet sheet = ExcelUtils.convertDataListToSheetRemoveNineAndOne(dataLists);
            //获取
            List<List<String>> getdata = ExcelDataUtils.getData(sheet);
            if (CollectionUtils.isEmpty(getdata)) {
                return AjaxResult.error("请填充数据");
            }

            List<String> groupName = new ArrayList<>();

            List<List<Object>> gruopDatas = new ArrayList<>();


            ChartConfigs configs = chartConfigsService.getById(configId);
            JSONObject jsonObject = JSON.parseObject(configs.getConfigValue());
            List<JSONObject> dataset = (List<JSONObject>) jsonObject.get("dataset");

            List<JSONObject> datasetList = new ArrayList<>();


            for (int i = 1; i < getdata.size(); i++) {
                List<Object> gruopData = new ArrayList<>();
                List<String> colData = new ArrayList<>();
                List<String> data = getdata.get(i);
                for (int i1 = 0; i1 < data.size(); i1++) {
                    String s = data.get(i1);
                    if (!ObjectUtils.isEmpty(s) && !s.equals("")) {
                        colData.add(s);
                    }
                }

                if (!CollectionUtils.isEmpty(colData)) {
                    if (i == getdata.size() - 1) {
                        JSONObject jsonObject1 = new JSONObject();
                        for (int i1 = 0; i1 < colData.size(); i1++) {
                            gruopData.add(Double.parseDouble(colData.get(i1)));
                        }
                        gruopDatas.add(gruopData);
                        jsonObject1.put("source", gruopDatas);
                        datasetList.add(jsonObject1);
                    } else if (i == 1) {
                        groupName.add(colData.get(0));
                    } else {
                        if (colData.size() == 1) {
                            groupName.add(colData.get(0));
                            JSONObject jsonObject1 = new JSONObject();
                            jsonObject1.put("source", gruopDatas);
                            datasetList.add(jsonObject1);
                            gruopDatas = new ArrayList<>();
                        } else {
                            for (int i1 = 0; i1 < colData.size(); i1++) {
                                gruopData.add(Double.parseDouble(colData.get(i1)));
                            }
                            gruopDatas.add(gruopData);
                        }
                    }
                }
            }

            List<JSONObject> series = (List<JSONObject>) jsonObject.get("series");
            ArrayList<JSONObject> seriesList = new ArrayList<>();
            JSONObject jsonObject1 = series.get(0);

            JSONObject jsonObject2 = dataset.get(dataset.size() - 1);
            for (int i = 0; i < groupName.size(); i++) {
                JSONObject jsonObject3 = new JSONObject();
                jsonObject3.putAll(jsonObject2);
                jsonObject3.put("fromDatasetIndex", i);
                datasetList.add(jsonObject3);

                JSONObject jsonObject4 = new JSONObject();
                jsonObject4.putAll(jsonObject1);
                jsonObject4.put("name", groupName.get(i));
                jsonObject4.put("datasetIndex", i + groupName.size());
                seriesList.add(jsonObject4);
            }
            jsonObject.put("dataset", datasetList);

            jsonObject.put("series", seriesList);

            JSONObject legend = (JSONObject) jsonObject.get("legend");

            ArrayList<Map> maps = new ArrayList<>();
            for (int i = 0; i < groupName.size(); i++) {
                Map map = new HashMap<>();
                map.put("name", groupName.get(i));
                maps.add(map);
            }

            legend.put("data", maps);
            jsonObject.put("legend", legend);

            return AjaxResult.success(JSON.toJSONString(jsonObject));
        } finally {
//            workbook.close();
        }
    }


}
